﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleLock
{
    class Program
    {
        public void RunMe()
        {
            Console.WriteLine("RunMe called");
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            //Program p = new Program();
            //p.Test(10);
            //开始多线程
            Console.WriteLine("开始测试静态方法的同步");
            for (int i = 0; i < 5; i++)
            {
                Thread t = new Thread(Lock.Increment1);
                t.Start();
               
            }
            //这里等待线程执行结束
            Thread.Sleep(5000);
            Console.WriteLine("开始测试成员方法的同步");
            Lock l = new Lock();
            //开始多线程
            for (int i = 0; i < 5; i++)
            {
                Thread t = new Thread(l.Increment2);
                t.Start();
            }
            Console.Read();
        }

        public void Test(int j)
        {
            lock (this)
            {
                if (j > 10)
                {
                    Console.WriteLine(j);
                    Console.ReadLine();
                    j--;
                    Test(j);
                }

            }
        }
    }
    /// <summary>
    /// 演示同步锁
    /// </summary>
    public class Lock
    {
        //用来在静态方法中同步
        private static Object o1 = new object();
        //用来在成员方法中不同
        private Object o2 = new object();
        //成员变量
        private static int i1 = 0;
        private int i2 = 0;
        /// <summary>
        /// 测试静态方法的同步
        /// </summary>
        /// <param name="state">状态对象</param>
        public static void Increment1(Object state)
        {
            lock (o1)
            {
                Console.WriteLine("i1的值为：{0}", i1.ToString());
                //这里刻意制造线程并行机会
                //来检查同步的功能
                Thread.Sleep(200);
                i1++;
                Console.WriteLine("i1自增后为：{0}", i1.ToString());
            }
        }
        /// <summary>
        /// 测试成员方法的同步
        /// </summary>
        /// <param name="state">状态对象</param>
        public void Increment2(Object state)
        {
            lock (o2)
            {
                Console.WriteLine("i2的值为：{0}", i2.ToString());
                //这里刻意制造线程并行机会
                //来检查同步的功能
                Thread.Sleep(200);
                i2++;
                Console.WriteLine("i2自增后为：{0}", i2.ToString());
            }
        }
    }
}
